package com.changanw.jedis;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

import java.util.List;

/**
 * redis 事务
 */
public class RedisTransactionTest {
    public static void main(String[] args) {
        new Redis().execute(jedis -> {
            final Integer money = new RedisTransactionTest().saveMoney(jedis, "changanw", 100000);
            System.out.println(money);

        });
    }

    public Integer saveMoney(Jedis jedis, String userId, Integer money) {

        while (true) {
            //监控一个key
            jedis.watch(userId);
            int v = Integer.parseInt(jedis.get(userId)) + money;
            //开启redis事务
            Transaction tx = jedis.multi();
            tx.set(userId, String.valueOf(v));
            //提交redis事务
            List<Object> exec = tx.exec();
            if (exec != null) {
                break;
            }
        }
        return Integer.parseInt(jedis.get(userId));
    }
}
